import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

const updateListeners: any = {}

// Custom APIs for renderer
const api = {
	minimizeWindow: () => ipcRenderer.invoke('window-minimize'),
	maximizeWindow: () => ipcRenderer.invoke('window-maximize'),
	closeWindow: () => ipcRenderer.invoke('window-close'),


  checkForUpdates: () => ipcRenderer.invoke('check-for-updates'),
  downloadUpdate: () => ipcRenderer.invoke('download-update'),
  quitAndInstall: () => ipcRenderer.invoke('quit-and-install'),
  getAppVersion: () => ipcRenderer.invoke('get-app-version'),

  // 更新事件监听
  onUpdateAvailable: (callback) => {
    updateListeners.updateAvailable = callback
    ipcRenderer.on('update-available', callback)
  },

  onUpdateNotAvailable: (callback) => {
    updateListeners.updateNotAvailable = callback
    ipcRenderer.on('update-not-available', callback)
  },

  onUpdateProgress: (callback) => {
    updateListeners.updateProgress = callback
    ipcRenderer.on('update-progress', callback)
  },

  onUpdateDownloaded: (callback) => {
    updateListeners.updateDownloaded = callback
    ipcRenderer.on('update-downloaded', callback)
  },

  onUpdateError: (callback) => {
    updateListeners.updateError = callback
    ipcRenderer.on('update-error', callback)
  },

  onUpdateStatus: (callback) => {
    updateListeners.updateStatus = callback
    ipcRenderer.on('update-status', callback)
  },

  // 移除所有监听器
  removeAllUpdateListeners: () => {
    Object.values(updateListeners).forEach((callback:any) => {
      if (callback) {
        ipcRenderer.removeAllListeners(callback)
      }
    })
  }
}

const gitApi = {
  // Git 操作
  cloneRepository: (url, username, password) =>
    ipcRenderer.invoke('git-clone', url, username, password),

  getCommitHistory: (repoPath, limit = 100) =>
    ipcRenderer.invoke('git-get-commit-history', repoPath, limit),

  modifyCommits: (repoPath, commits) =>
    ipcRenderer.invoke('git-modify-commits', repoPath, commits),

  pushChanges: (repoPath, username, password) =>
    ipcRenderer.invoke('git-push-changes', repoPath, username, password),

  // 文件操作
  selectDirectory: () => ipcRenderer.invoke('select-directory'),

  // 工具函数
  showDialog: (options) => ipcRenderer.invoke('show-dialog', options)

}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('electronApi', api)
    contextBridge.exposeInMainWorld('gitApi', gitApi)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.electronApi = api
  // @ts-ignore (define in dts)
  window.gitApi = gitApi
}


